/*
 * TaskManagerView.java
 */
package taskmanager;

import com.imagine.component.calendar.events.CalendarEvent;
import javax.swing.table.TableModel;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import com.imagine.component.calendar.*;
import java.util.*;
import org.jdesktop.application.Application;
import com.imagine.component.calendar.*;
import com.imagine.component.calendar.data.CalendarMonthType;
import javax.swing.table.DefaultTableModel;
import com.imagine.component.calendar.events.*;
import com.imagine.util.events.MouseEventType;
import javax.swing.SpinnerModel;

import javax.swing.ImageIcon;

/**
 * The application's main frame.
 */
public class TaskManagerView extends FrameView implements CalendarComponentListener/* ActionListener, ysTrayMenuListener*/ {

    private Controller controller;
    private boolean newTask = true;
    private boolean dateSelected = false;
    /*private SysTrayMenu menu;
    int currentIndexIcon;
    int currentIndexTooltip;
    
    private static final String[] toolTips =
    {
        "SysTray for Java rules!",
        "brought to you by\nSnoozeSoft 2004"
    };

    // create icons
    static final SysTrayMenuIcon[] icons =
    {
        // the extension can be omitted
        new SysTrayMenuIcon( "icons/duke" ),
        new SysTrayMenuIcon( "icons/duke_up" )
    };

    public void actionPerformed( ActionEvent e )
    {
        if( e.getActionCommand().equals( "change tooltip" ) )
        {
            if( currentIndexTooltip == 0 ) currentIndexTooltip = 1;
            else currentIndexTooltip = 0;

            menu.setToolTip( toolTips[ currentIndexTooltip ] );
        }
        else if( e.getActionCommand().equals( "change icon" ) )
        {
            if( currentIndexIcon == 0 ) currentIndexIcon = 1;
            else currentIndexIcon = 0;

            menu.setIcon( icons[ currentIndexIcon ] );
        }
        else if( e.getActionCommand().equals( "show/hide icon" ) )
        {
            if( menu.isIconVisible() ) menu.hideIcon();
            else menu.showIcon();
        }
        else if( e.getActionCommand().equals( "enable/disable submenu" ) )
        {
            SysTrayMenuItem item = menu.getItem( "Communication" );
            if( item.isEnabled() ) item.setEnabled( false );
            else item.setEnabled( true );
        }
    }

    public void menuItemSelected(SysTrayMenuEvent e) {
        if( e.getActionCommand().equals( "exit" ) ) 
            System.exit( 0 );
    }

    public void iconLeftClicked(SysTrayMenuEvent stme) {
        if( this.getFrame().isVisible() ) 
            this.getFrame().hide();
        else this.getFrame().show();
    }

    public void iconLeftDoubleClicked(SysTrayMenuEvent stme) {
    }
    
    
    void createMenu()
    {
        // create some labeled menu items
        SysTrayMenuItem subItem1 = new SysTrayMenuItem( "Task Manager", "task manager" );
        subItem1.addSysTrayMenuListener( this );

        // create an exit item
        SysTrayMenuItem itemExit = new SysTrayMenuItem( "Exit", "exit" );
        itemExit.addSysTrayMenuListener( this );

        // create the main menu
        menu = new SysTrayMenu( icons[ 0 ], toolTips[ 0 ] );

        // insert items
        menu.addItem( itemExit );
        menu.addSeparator();
        menu.addItem(subItem1);
    }
    */
    public class UpdateTableTask extends TimerTask{

        @Override
        public void run() {
            if (controller.getMustUpdate())
                UpdateAll();
        }
        
    }

    public TaskManagerView(SingleFrameApplication app, Controller controller) {
        super(app);

        this.controller = controller;

        initComponents();       
        ClearInput();
        UpdateAll();
        calendar.addCalendarComponentListener(this);
        
        //this.getFrame().setIconImage( new ImageIcon(
        //    this.getFrame().getClass().getResource( "rocket.gif" ) ).getImage() );
        //createMenu();
        
        java.util.Timer timer = new java.util.Timer();
        timer.scheduleAtFixedRate(new UpdateTableTask(), new Date(), controller.getPeriod());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        calendarDate = new com.imagine.component.calendar.CalendarComboBox();
        calendar = new com.imagine.component.calendar.CalendarComponent();
        eName = new javax.swing.JTextField();
        spinHours = new javax.swing.JSpinner();
        jScrollPane2 = new javax.swing.JScrollPane();
        eDescription = new javax.swing.JTextPane();
        btnSaveTask = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtClosed = new javax.swing.JTextField();
        txtRemaining = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        eContacts = new javax.swing.JTextPane();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel2 = new javax.swing.JPanel();
        btnRemoveTask = new javax.swing.JButton();
        btnAddTask = new javax.swing.JButton();
        spinMinutes = new javax.swing.JSpinner();
        btnCloseTask = new javax.swing.JButton();
        btnShowAll = new javax.swing.JButton();

        mainPanel.setMaximumSize(new java.awt.Dimension(0, 0));
        mainPanel.setMinimumSize(new java.awt.Dimension(500, 500));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(500, 900));
        mainPanel.setVerifyInputWhenFocusTarget(false);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        table.setAutoCreateRowSorter(true);
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null}
            },
            new String [] {
                "ID", "Task", "Due Date", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.setName("table"); // NOI18N
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table.getTableHeader().setReorderingAllowed(false);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(taskmanager.TaskManagerApp.class).getContext().getResourceMap(TaskManagerView.class);
        table.getColumnModel().getColumn(0).setMinWidth(0);
        table.getColumnModel().getColumn(0).setPreferredWidth(0);
        table.getColumnModel().getColumn(0).setMaxWidth(0);
        table.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("table.columnModel.title0")); // NOI18N
        table.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("table.columnModel.title1")); // NOI18N
        table.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("table.columnModel.title2")); // NOI18N
        table.getColumnModel().getColumn(3).setMinWidth(60);
        table.getColumnModel().getColumn(3).setPreferredWidth(60);
        table.getColumnModel().getColumn(3).setMaxWidth(80);
        table.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("table.columnModel.title3")); // NOI18N

        calendarDate.setToolTipText(resourceMap.getString("calendarDate.toolTipText")); // NOI18N
        calendarDate.setName("calendarDate"); // NOI18N

        calendar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("calendar.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("calendar.border.titleFont"))); // NOI18N
        calendar.setName("calendar"); // NOI18N

        eName.setText(resourceMap.getString("eName.text")); // NOI18N
        eName.setToolTipText(resourceMap.getString("eName.toolTipText")); // NOI18N
        eName.setName("eName"); // NOI18N

        spinHours.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), null, Integer.valueOf(23), Integer.valueOf(1)));
        spinHours.setToolTipText(resourceMap.getString("spinHours.toolTipText")); // NOI18N
        spinHours.setEditor(new javax.swing.JSpinner.NumberEditor(spinHours, ""));
        spinHours.setName("spinHours"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        eDescription.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("eDescription.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("eDescription.border.titleFont"))); // NOI18N
        eDescription.setToolTipText(resourceMap.getString("eDescription.toolTipText")); // NOI18N
        eDescription.setName("eDescription"); // NOI18N
        jScrollPane2.setViewportView(eDescription);

        btnSaveTask.setText(resourceMap.getString("btnSaveTask.text")); // NOI18N
        btnSaveTask.setToolTipText(resourceMap.getString("btnSaveTask.toolTipText")); // NOI18N
        btnSaveTask.setName("btnSaveTask"); // NOI18N
        btnSaveTask.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnSaveTaskMouseClicked(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel1.border.titleFont"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtClosed.setEditable(false);
        txtClosed.setText(resourceMap.getString("txtClosed.text")); // NOI18N
        txtClosed.setToolTipText(resourceMap.getString("txtClosed.toolTipText")); // NOI18N
        txtClosed.setName("txtClosed"); // NOI18N

        txtRemaining.setEditable(false);
        txtRemaining.setText(resourceMap.getString("txtRemaining.text")); // NOI18N
        txtRemaining.setToolTipText(resourceMap.getString("txtRemaining.toolTipText")); // NOI18N
        txtRemaining.setName("txtRemaining"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtRemaining)
                    .addComponent(txtClosed, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtClosed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRemaining, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(108, Short.MAX_VALUE))
        );

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        eContacts.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("eContacts.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("eContacts.border.titleFont"))); // NOI18N
        eContacts.setToolTipText(resourceMap.getString("eContacts.toolTipText")); // NOI18N
        eContacts.setName("eContacts"); // NOI18N
        jScrollPane3.setViewportView(eContacts);

        jSeparator1.setName("jSeparator1"); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        btnRemoveTask.setIcon(resourceMap.getIcon("btnRemoveTask.icon")); // NOI18N
        btnRemoveTask.setToolTipText(resourceMap.getString("btnRemoveTask.toolTipText")); // NOI18N
        btnRemoveTask.setFocusable(false);
        btnRemoveTask.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnRemoveTask.setIconTextGap(0);
        btnRemoveTask.setMaximumSize(new java.awt.Dimension(30, 30));
        btnRemoveTask.setMinimumSize(new java.awt.Dimension(20, 20));
        btnRemoveTask.setName("btnRemoveTask"); // NOI18N
        btnRemoveTask.setPreferredSize(new java.awt.Dimension(16, 16));
        btnRemoveTask.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnRemoveTask.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnRemoveTaskMouseClicked(evt);
            }
        });

        btnAddTask.setIcon(resourceMap.getIcon("btnAddTask.icon")); // NOI18N
        btnAddTask.setToolTipText(resourceMap.getString("btnAddTask.toolTipText")); // NOI18N
        btnAddTask.setFocusable(false);
        btnAddTask.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddTask.setIconTextGap(0);
        btnAddTask.setMaximumSize(new java.awt.Dimension(30, 30));
        btnAddTask.setMinimumSize(new java.awt.Dimension(20, 20));
        btnAddTask.setName("btnAddTask"); // NOI18N
        btnAddTask.setPreferredSize(new java.awt.Dimension(16, 16));
        btnAddTask.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddTask.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAddTaskMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnRemoveTask, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)
                    .addComponent(btnAddTask, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnRemoveTask, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAddTask, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(113, Short.MAX_VALUE))
        );

        spinMinutes.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), null, Integer.valueOf(59), Integer.valueOf(1)));
        spinMinutes.setToolTipText(resourceMap.getString("spinMinutes.toolTipText")); // NOI18N
        spinMinutes.setEditor(new javax.swing.JSpinner.NumberEditor(spinMinutes, ""));
        spinMinutes.setName("spinMinutes"); // NOI18N

        btnCloseTask.setText(resourceMap.getString("btnCloseTask.text")); // NOI18N
        btnCloseTask.setName("btnCloseTask"); // NOI18N
        btnCloseTask.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCloseTaskMouseClicked(evt);
            }
        });

        btnShowAll.setText(resourceMap.getString("btnShowAll.text")); // NOI18N
        btnShowAll.setName("btnShowAll"); // NOI18N
        btnShowAll.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnShowAllMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(calendar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(btnShowAll, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSaveTask, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                            .addComponent(eName, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(calendarDate, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(spinHours, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(spinMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(88, 88, 88))
                            .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(btnCloseTask, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 577, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE))
                .addGap(115, 115, 115))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(calendar, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(btnShowAll, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(eName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(spinMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(spinHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(calendarDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(11, 11, 11)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane3)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(btnSaveTask, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnCloseTask, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
                                .addGap(14, 14, 14)))))
                .addContainerGap())
        );

        setComponent(mainPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveTaskMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSaveTaskMouseClicked
        Calendar theDate = new GregorianCalendar();
        theDate.setTime(calendarDate.getDate());
        theDate.set(Calendar.HOUR_OF_DAY, (Integer)spinHours.getValue());
        theDate.set(Calendar.MINUTE, (Integer)spinMinutes.getValue());
        theDate.set(Calendar.SECOND, 0);
        theDate.set(Calendar.MILLISECOND, 0);
        
        if (!controller.validateDate(theDate.getTime())){
                new ErrorFrame("Put a date after now").setVisible(true);
                return;
        }
            
        if (newTask){          
                    
            TaskInfo task = controller.createTask(eName.getText(), eDescription.getText(), eContacts.getText(), theDate.getTime());
           
            DefaultTableModel model1 = (DefaultTableModel) table.getModel();
            Vector rowData = new Vector();
            rowData.add(task.getId());
            rowData.add(task.getName());
            rowData.add(task.getDueDate());
            rowData.add(task.isClosed()? "closed" : "open");
            model1.addRow(rowData);
            table.setModel(model1);
            table.setRowSelectionInterval(table.getRowCount()-1,table.getRowCount()-1);            
        }
        else{
            List<TaskInfo> list = controller.getAll();
            int a = table.getSelectedRow();
            if (a < 0)
                return;
            int id = (Integer) table.getValueAt(a, 0);
            TaskInfo task = controller.findById(id);
            
            if (task == null){
                new ErrorFrame("task not found").setVisible(true);
                return;
            }
            
            controller.editTask(id,eName.getText(), eDescription.getText(), eContacts.getText(), theDate.getTime());
        
            DefaultTableModel model1 = (DefaultTableModel) table.getModel();
            Vector rowData = new Vector();
            rowData.add(id);
            rowData.add(eName.getText());
            rowData.add(calendarDate.getDate());
            rowData.add(task.isClosed()? "closed" : "open");
            model1.removeRow(a);
            model1.insertRow(a, rowData);
            table.setModel(model1);
            table.setRowSelectionInterval(a, a);
        }         
              
        UpdateAll();
        ClearInput();
    }//GEN-LAST:event_btnSaveTaskMouseClicked

    private void btnAddTaskMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAddTaskMouseClicked
        // TODO add your handling code here:
        ClearInput();        
        dateSelected = false;     
    }//GEN-LAST:event_btnAddTaskMouseClicked

    private void btnRemoveTaskMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRemoveTaskMouseClicked
        // TODO add your handling code here:
        List<TaskInfo> list = controller.getAll();
        int a = table.getSelectedRow();
        if (a < 0)
            return;
        int id = (Integer) table.getValueAt(a, 0);
        
        controller.removeTask(id);
        table.removeRowSelectionInterval(a, a);
        
        ClearInput();
        UpdateAll();
    }//GEN-LAST:event_btnRemoveTaskMouseClicked

    private void btnCloseTaskMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCloseTaskMouseClicked
        newTask = false;
        
        List<TaskInfo> list = controller.getAll();
        int a = table.getSelectedRow();
        if (a < 0)
            return;
        int id = (Integer) table.getValueAt(a, 0);
        
        controller.closeTask(id);
        UpdateAll();
    }//GEN-LAST:event_btnCloseTaskMouseClicked

    private void btnShowAllMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnShowAllMouseClicked
        newTask = false;
        dateSelected = false; 
        UpdateTable();
        UpdateStatistics();
    }//GEN-LAST:event_btnShowAllMouseClicked

    private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
        newTask = false;
        List<TaskInfo> list = controller.getAll();
        int a = table.getSelectedRow();
        if (a < 0)
            return;
        int id = (Integer) table.getValueAt(a, 0);
        TaskInfo task = controller.findById(id);
        
        Calendar theDate = new GregorianCalendar();
        theDate.setTime(task.getDueDate());
        
        eName.setText(task.getName());
        eDescription.setText(task.getDescription());
        eContacts.setText(task.getContacts());
        
        Calendar now = new GregorianCalendar();
        calendarDate.setDate(theDate.getTime());
        spinHours.setValue(theDate.get(Calendar.HOUR_OF_DAY));
        spinMinutes.setValue(theDate.get(Calendar.MINUTE));
    }//GEN-LAST:event_tableMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddTask;
    private javax.swing.JButton btnCloseTask;
    private javax.swing.JButton btnRemoveTask;
    private javax.swing.JButton btnSaveTask;
    private javax.swing.JButton btnShowAll;
    private com.imagine.component.calendar.CalendarComponent calendar;
    private com.imagine.component.calendar.CalendarComboBox calendarDate;
    private javax.swing.JTextPane eContacts;
    private javax.swing.JTextPane eDescription;
    private javax.swing.JTextField eName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JSpinner spinHours;
    private javax.swing.JSpinner spinMinutes;
    private javax.swing.JTable table;
    private javax.swing.JTextField txtClosed;
    private javax.swing.JTextField txtRemaining;
    // End of variables declaration//GEN-END:variables

    public Class[] getEventsListened() {
        //throw new UnsupportedOperationException("Not supported yet.");
        Class[] a = new Class[1];
        a[0] = new CalendarEventDateSelectedByMouse(calendar, CalendarMonthType.NEXT_MONTH, null).getClass();
        return a;
       
    }

    // TODO Somehow process a calendar event
    public void processCalendarEvent(CalendarEvent ce) {
        if (ce instanceof CalendarEventDateSelectedByMouse){ 
            newTask = false;
            UpdateTableOnDate();
        }
    }
    
    public void UpdateStatistics(){
        StatisticInfo info = controller.calculateStatistics();
        this.txtClosed.setText(((Integer)info.numClosed).toString());
        this.txtRemaining.setText(((Integer)info.numRemaining).toString());
    }
    
    private void UpdateTable(){
        DefaultTableModel model1 = (DefaultTableModel) table.getModel();
        List<TaskInfo> list = controller.getAll();
        model1.setRowCount(0);
        for (TaskInfo task : list) {
            Vector rowData = new Vector();
            rowData.add(task.getId());
            rowData.add(task.getName());
            rowData.add(task.getDueDate());
            rowData.add(task.isClosed()? "closed" : "open");
            model1.addRow(rowData);
            table.setModel(model1);
        }
    }
    
    private void UpdateTableOnDate(){
        DefaultTableModel model1 = (DefaultTableModel) table.getModel();
        List<TaskInfo> tasksOnDate = controller.tasksOnDate(calendar.getDate());
        model1.setRowCount(0);
        for (TaskInfo task : tasksOnDate) {
            Vector rowData = new Vector();
            rowData.add(task.getId());
            rowData.add(task.getName());
            rowData.add(task.getDueDate());
            rowData.add(task.isClosed()? "closed" : "open");
            model1.addRow(rowData);
            table.setModel(model1);
        }  
    }
    
    private void UpdateAll(){
        if (dateSelected){
            UpdateTableOnDate();
        }
        else{
            UpdateTable();
        }
        UpdateStatistics();    
    }
    
    private void ClearInput(){
        eName.setText("");
        eDescription.setText("");
        eContacts.setText("");
        
        Calendar now = new GregorianCalendar();
        calendarDate.setDate(now.getTime());
        spinHours.setValue(now.get(Calendar.HOUR_OF_DAY));
        spinMinutes.setValue(now.get(Calendar.MINUTE)+1);
        
        newTask = true;
    }
}
